package com.hx.update.utils;

import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class DownloadUtil {
    private static final String TAG = "HXDownloadUtil";
    private static final int DOWNLOAD_FAIL = 0;
    private static final int DOWNLOAD_PROGRESS = 1;
    private static final int DOWNLOAD_SUCCESS = 2;
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;
    private DownloadListener listener;
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case DOWNLOAD_PROGRESS:
                    listener.onDownloading((Long) msg.obj);
                    break;
                case DOWNLOAD_FAIL:
                    listener.onDownloadFailed((String) msg.obj);
                    break;
                case DOWNLOAD_SUCCESS:
                    listener.onDownloadSuccess((String) msg.obj);
                    break;
            }
        }
    };

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    public static DownloadUtil getInstance() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    /**
     *
     */
    public void download(final String url, final String saveDir, final DownloadListener listener) {
        this.listener = listener;
//        if (isExists(url, saveDir)) {
//            // 已存在该下载文件，直接安装
//            Log.e(TAG, "已存在该下载文件，直接安装");
//            Message message = Message.obtain();
//            message.what = DOWNLOAD_SUCCESS;
//            message.obj = savedFilePath;
//            mHandler.sendMessage(message);
//            return;
//        }
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Message message = Message.obtain();
                message.what = DOWNLOAD_FAIL;
                message.obj = "下载失败，请稍后重试";
                mHandler.sendMessage(message);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
//                Log.e(TAG, "response: " + response);
                if (200 != response.code()) {
                    Message message = Message.obtain();
                    message.what = DOWNLOAD_FAIL;
                    message.obj = "下载失败，请稍后重试";
                    mHandler.sendMessage(message);
                    return;
                }
                InputStream is = null;
                byte[] buf = new byte[1024 * 4];
                int len;
                FileOutputStream fos = null;
                //储存下载文件的目录
                String savePath = isExistDir(saveDir);
                try {
                    is = response.body().byteStream();
//                    long total = response.body().contentLength();
//                    Log.e(TAG, "total: " + total);
                    File file = new File(savePath, getNameFromUrl(url));
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
//                        int progress = (int) (sum * 1.0f / total * 100);
//                        Log.e(TAG, "progress: " + progress);
                        //下载中
                        Message message = Message.obtain();
                        message.what = DOWNLOAD_PROGRESS;
                        message.obj = sum;
                        mHandler.sendMessage(message);
                    }
                    fos.flush();
                    //下载完成
                    Message message = Message.obtain();
                    message.what = DOWNLOAD_SUCCESS;
                    message.obj = file.getAbsolutePath();
                    mHandler.sendMessage(message);
                } catch (Exception e) {
                    Message message = Message.obtain();
                    message.what = DOWNLOAD_FAIL;
                    message.obj = "下载失败，请稍后重试";
                    mHandler.sendMessage(message);
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private String getNameFromUrl(String url) {
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        if (!fileName.endsWith(".apk")) {
            fileName = "answer.apk";
        }
        return fileName;
    }

    private String isExistDir(String saveDir) throws IOException {
        File downloadFile = new File(saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        return downloadFile.getAbsolutePath();
    }

    private boolean isExists(String url, String saveDir) {
        File dir = new File(saveDir);
        if (!dir.exists() || !dir.isDirectory()) {
            return false;
        }

        String fileName = getNameFromUrl(url);
        String savedFilePath = saveDir + getNameFromUrl(url);
        if (TextUtils.isEmpty(fileName)) {
            return false;
        }

        File file;
        try {
            file = new File(savedFilePath);
        } catch (Exception e) {
            return false;
        }
        return file.exists();
    }

    public interface DownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess(String path);

        /**
         * 下载进度
         *
         * @param progress progress
         */
        void onDownloading(long progress);

        /**
         * 下载失败
         */
        void onDownloadFailed(String err);
    }
}
